<template>
  <div class="transaction-partner-stats">
    <div class="header-actions">
      <el-date-picker
        v-model="dateRange"
        type="datetimerange"
        range-separator="至"
        start-placeholder="开始日期时间"
        end-placeholder="结束日期时间"
        value-format="yyyy-MM-dd HH:mm:ss"
        @change="handleDateRangeChange"
        style="width: 400px;"
      />
      <!-- 快速时间范围选择 -->
      <div style="display: flex; gap: 5px;">
        <el-button 
          :type="quickDateRange === 'today' ? 'primary' : 'default'"
          @click="setQuickDateRange('today')">今天</el-button>
        <el-button 
          :type="quickDateRange === 'week' ? 'primary' : 'default'"
          @click="setQuickDateRange('week')">最近一周</el-button>
        <el-button 
          :type="quickDateRange === 'month' ? 'primary' : 'default'"
          @click="setQuickDateRange('month')">最近一月</el-button>
        <el-button 
          :type="quickDateRange === 'halfYear' ? 'primary' : 'default'"
          @click="setQuickDateRange('halfYear')">最近半年</el-button>
        <el-button 
          :type="quickDateRange === 'year' ? 'primary' : 'default'"
          @click="setQuickDateRange('year')">最近一年</el-button>
      </div>
      <el-input
        v-model="transactionPartnerFilter"
        placeholder="请输入交易对象名称"
        style="width: 200px;"
        @keyup.enter="fetchStats"
      />
      <el-button type="primary" @click="fetchStats">查询</el-button>
      <el-button @click="resetFilters">重置</el-button>
    </div>

    <div class="stats-content">
      <el-table :data="statsData" style="width: 100%" show-summary :summary-method="getSummaries" v-loading="false" ref="table" :cell-style="cellStyle" height="calc(100vh - 220px)">
        <el-table-column prop="transactionPartner" label="交易对象" min-width="200" />
        <el-table-column prop="count" label="交易笔数" />
        <el-table-column prop="totalIncome" label="总收入" :formatter="formatCurrency" />
        <el-table-column prop="totalExpense" label="总支出" :formatter="formatCurrency" />
        <el-table-column prop="netAmount" label="净额" :formatter="formatCurrency" />
      </el-table>
    </div>
  </div>
</template>

<script>
import { transactionService } from '@/api/transactionService'

export default {
  name: 'TransactionPartnerStats',
  data() {
    return {
      statsData: [],
      dateRange: null,
      transactionPartnerFilter: '',
      netAmountSummaryValue: 0,
      quickDateRange: '' // 快速时间范围：today, week, month, halfYear, year
    };
  },
  created() {
    this.fetchStats();
  },
  methods: {
    async fetchStats() {
      try {
        const params = {};
        if (this.dateRange && this.dateRange.length === 2) {
          params.startTime = this.dateRange[0];
          params.endTime = this.dateRange[1];
        }
        if (this.transactionPartnerFilter.trim()) {
          params.transactionPartner = this.transactionPartnerFilter.trim();
        }
        const response = await transactionService.getTransactionPartnerStats(params);
        if (response.code === 200) {
          this.statsData = response.data || [];
          // 数据加载完成后，重新计算并更新合计行样式
          this.$nextTick(() => {
            // 触发getSummaries重新执行
            if (this.$refs.table && this.$refs.table.doLayout) {
              this.$refs.table.doLayout();
            }
          });
        } else {
          this.$message.error('获取统计数据失败');
        }
      } catch (error) {
        this.$message.error('获取统计数据失败');
        console.error('获取统计数据失败:', error);
      }
    },
    handleDateRangeChange() {
      // 日期范围变化时自动查询
      this.fetchStats();
    },
    resetFilters() {
      this.dateRange = null;
      this.transactionPartnerFilter = '';
      this.quickDateRange = '';
      this.fetchStats();
    },
    
    // 设置快速时间范围
    setQuickDateRange(type) {
      this.quickDateRange = type
      const now = new Date()
      const endTime = new Date(now)
      endTime.setHours(23, 59, 59, 999)
      
      const startTime = new Date()
      
      switch(type) {
        case 'today':
          // 今天：从00:00:00到23:59:59
          startTime.setHours(0, 0, 0, 0)
          break
        case 'week':
          // 最近一周：从7天前的00:00:00到今天的23:59:59
          startTime.setDate(now.getDate() - 7)
          startTime.setHours(0, 0, 0, 0)
          break
        case 'month':
          // 最近一个月：从30天前的00:00:00到今天的23:59:59
          startTime.setDate(now.getDate() - 30)
          startTime.setHours(0, 0, 0, 0)
          break
        case 'halfYear':
          // 最近半年：从180天前的00:00:00到今天的23:59:59
          startTime.setDate(now.getDate() - 180)
          startTime.setHours(0, 0, 0, 0)
          break
        case 'year':
          // 最近一年：从365天前的00:00:00到今天的23:59:59
          startTime.setDate(now.getDate() - 365)
          startTime.setHours(0, 0, 0, 0)
          break
      }
      
      // 格式化为yyyy-MM-dd HH:mm:ss
      const formatDateTime = (date) => {
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        const hours = String(date.getHours()).padStart(2, '0')
        const minutes = String(date.getMinutes()).padStart(2, '0')
        const seconds = String(date.getSeconds()).padStart(2, '0')
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
      }
      
      this.dateRange = [formatDateTime(startTime), formatDateTime(endTime)]
      this.fetchStats()
    },
    formatCurrency(row, column, cellValue) {
      if (cellValue === null || cellValue === undefined) return '0.00';
      return parseFloat(cellValue).toFixed(2);
    },
    cellStyle({ row, column }) {
      // 简化的样式逻辑
      if (column.property === 'netAmount' && row && row.netAmount !== undefined) {
        if (parseFloat(row.netAmount) < 0) {
          return { color: 'red' };
        } else if (parseFloat(row.netAmount) > 0) {
          return { color: 'green' };
        }
      }
      return {};
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      let netAmountSum = 0;
      
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }
        if (column.property === 'count') {
          const values = data.map(item => Number(item.count) || 0);
          const sum = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + value;
            } else {
              return prev;
            }
          }, 0);
          sums[index] = sum;
        } else if (column.property === 'totalIncome' || column.property === 'totalExpense' || column.property === 'netAmount') {
          const values = data.map(item => Number(item[column.property]) || 0);
          const sum = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + value;
            } else {
              return prev;
            }
          }, 0);
          if (column.property === 'netAmount') {
            netAmountSum = sum;
          }
          sums[index] = sum.toFixed(2);
        } else {
          sums[index] = '';
        }
      });
      
      // 更新净额合计值
      this.netAmountSummaryValue = netAmountSum;
      
      return sums;
    }
  }
};
</script>

<style scoped>
.transaction-partner-stats {
  padding: 20px;
  background-color: #fff;
}

.header-actions {
  margin-bottom: 20px;
  display: flex;
  gap: 15px;
  align-items: center;
  flex-wrap: wrap;
  padding: 10px 0;
}

.stats-content {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  margin-top: 10px;
  height: calc(100vh - 200px);
  overflow: hidden;
}

/* 自定义合计行样式 */
::v-deep .el-table__footer-wrapper .el-table__footer {
  font-weight: bold;
  background-color: #fafafa;
}

::v-deep .el-table__footer-wrapper .el-table__row {
  background-color: #fafafa;
}

/* 金额合计的颜色样式 */
::v-deep .el-table__footer-wrapper .el-table__cell:last-child {
  font-weight: bold;
}


</style>